package com.example.remotecontrol.ui.devices

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.wifi.WifiManager
import android.os.Build
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.remotecontrol.util.BluetoothManager as BtManager
import com.example.remotecontrol.util.WiFiManager as WifiMgr
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import java.net.InetAddress
import javax.inject.Inject

/**
 * 设备发现状态
 */
enum class DeviceDiscoveryState {
    IDLE, SCANNING, COMPLETED, ERROR
}

/**
 * 设备发现视图模型
 */
@HiltViewModel
class DeviceDiscoveryViewModel @Inject constructor(
    @ApplicationContext private val context: Context,
    private val bluetoothManager: BtManager,
    private val wifiManager: WifiMgr
) : ViewModel() {
    
    private val _deviceDiscoveryState = MutableStateFlow(DeviceDiscoveryState.IDLE)
    val deviceDiscoveryState: StateFlow<DeviceDiscoveryState> = _deviceDiscoveryState.asStateFlow()
    
    private val _bluetoothDevices = MutableStateFlow<List<BluetoothDevice>>(emptyList())
    val bluetoothDevices: StateFlow<List<BluetoothDevice>> = _bluetoothDevices.asStateFlow()
    
    private val _wifiDevices = MutableStateFlow<List<InetAddress>>(emptyList())
    val wifiDevices: StateFlow<List<InetAddress>> = _wifiDevices.asStateFlow()
    
    private val _scanningBluetooth = MutableStateFlow(false)
    val scanningBluetooth: StateFlow<Boolean> = _scanningBluetooth.asStateFlow()
    
    private val _scanningWifi = MutableStateFlow(false)
    val scanningWifi: StateFlow<Boolean> = _scanningWifi.asStateFlow()
    
    private val btDevicesList = mutableListOf<BluetoothDevice>()
    private val btDiscoveryReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            when (intent.action) {
                BluetoothDevice.ACTION_FOUND -> {
                    val device: BluetoothDevice? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                        intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE, BluetoothDevice::class.java)
                    } else {
                        @Suppress("DEPRECATION")
                        intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
                    }
                    
                    device?.let {
                        val deviceName = it.name ?: "未知设备"
                        Log.d("DeviceDiscovery", "发现蓝牙设备: $deviceName (${it.address})")
                        
                        if (!btDevicesList.contains(it)) {
                            btDevicesList.add(it)
                            _bluetoothDevices.value = btDevicesList.toList()
                        }
                    }
                }
                BluetoothAdapter.ACTION_DISCOVERY_FINISHED -> {
                    _scanningBluetooth.value = false
                    Log.d("DeviceDiscovery", "蓝牙设备扫描完成")
                    
                    if (btDevicesList.isEmpty() && !_scanningWifi.value) {
                        _deviceDiscoveryState.value = DeviceDiscoveryState.COMPLETED
                    }
                }
            }
        }
    }
    
    /**
     * 初始化
     */
    init {
        // 注册蓝牙发现广播接收器
        val filter = IntentFilter().apply {
            addAction(BluetoothDevice.ACTION_FOUND)
            addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)
        }
        context.registerReceiver(btDiscoveryReceiver, filter)
        
        // 获取已配对的蓝牙设备
        viewModelScope.launch(Dispatchers.IO) {
            val pairedDevices = bluetoothManager.getPairedDevices()
            if (pairedDevices.isNotEmpty()) {
                btDevicesList.addAll(pairedDevices)
                _bluetoothDevices.value = btDevicesList.toList()
            }
        }
    }
    
    /**
     * 开始蓝牙设备发现
     */
    fun startBluetoothDiscovery() {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                _scanningBluetooth.value = true
                _deviceDiscoveryState.value = DeviceDiscoveryState.SCANNING
                
                // 清除之前的结果
                btDevicesList.clear()
                _bluetoothDevices.value = emptyList()
                
                // 获取已配对设备
                val pairedDevices = bluetoothManager.getPairedDevices()
                if (pairedDevices.isNotEmpty()) {
                    btDevicesList.addAll(pairedDevices)
                    _bluetoothDevices.value = btDevicesList.toList()
                }
                
                // 开始搜索新设备
                bluetoothManager.startDiscovery()
                
            } catch (e: Exception) {
                Log.e("DeviceDiscovery", "蓝牙设备扫描出错", e)
                _scanningBluetooth.value = false
                _deviceDiscoveryState.value = DeviceDiscoveryState.ERROR
            }
        }
    }
    
    /**
     * 开始WiFi设备发现
     */
    fun startWifiDiscovery() {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                _scanningWifi.value = true
                _deviceDiscoveryState.value = DeviceDiscoveryState.SCANNING
                
                // 清除之前的结果
                _wifiDevices.value = emptyList()
                
                // 在后台线程上执行网络发现
                val devices = wifiManager.discoverDevices()
                _wifiDevices.value = devices
                
                _scanningWifi.value = false
                
                if (devices.isEmpty() && !_scanningBluetooth.value) {
                    _deviceDiscoveryState.value = DeviceDiscoveryState.COMPLETED
                }
                
            } catch (e: Exception) {
                Log.e("DeviceDiscovery", "WiFi设备扫描出错", e)
                _scanningWifi.value = false
                _deviceDiscoveryState.value = DeviceDiscoveryState.ERROR
            }
        }
    }
    
    /**
     * 清除资源
     */
    override fun onCleared() {
        super.onCleared()
        
        try {
            context.unregisterReceiver(btDiscoveryReceiver)
        } catch (e: Exception) {
            // 忽略接收器未注册的异常
        }
        
        // 确保停止蓝牙发现
        if (_scanningBluetooth.value) {
            bluetoothManager.stopDiscovery()
        }
    }
} 